import 'package:flutter/material.dart';
import 'package:flutter_base_app/export.dart';
import 'package:webview_flutter_plus/webview_flutter_plus.dart';
import '../../../widgets/base/get_rx_widget.dart';
import '../../vm/other/h5_vm.dart';

///
class H5Page extends BasePage {
  const H5Page({super.key});

  @override
  State<H5Page> createState() => _H5PageState();
}

class _H5PageState extends BaseMvvmState<H5Page, H5Vm> {
  _H5PageState() : super(H5Vm());
  late final WebViewControllerPlus _controller;
  String url = "";
  bool dayNight = false;
  final _loadingProgress = 0.obs;
  final _isLoading = false.obs;

  void refreshTitle() async {
    title.value = (await _controller.getTitle()) ?? "";
  }

  @override
  void initState() {
    super.initState();
    url = RouterJump.arguments['url'] ?? "";
    dayNight = RouterJump.arguments['otherParams']?['dayNight'] ?? false;
    LogUtils.e("H5页面参数 ${RouterJump.arguments}");
    if (dayNight) {
      url = url.contains("?") ? "$url&theme=light" : "$url?theme=light";
    }
    LogUtils.e("当前加载的URL = $url");

    title.value = RouterJump.arguments['title'] ?? "";

    _controller = WebViewControllerPlus()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel("vinka", onMessageReceived: (JavaScriptMessage message) {
        print(message.message);
      })
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (url) async {
            // 注入 JS 代码覆盖 navigator.language,修改成本软件设置的语言
            String jsCode =
                "Object.defineProperty(navigator, 'language', { value: '${I18nConfig.locale}', configurable: false });";
            _controller.runJavaScript(jsCode);
            _isLoading.value = true;
            _loadingProgress.value = 0;
            await getScope().delay(300);
            refreshTitle();
          },
          onProgress: (progress) {
            _loadingProgress.value = progress;
          },
          onPageFinished: (url) {
            _isLoading.value = false;
            _loadingProgress.value = 100;
            refreshTitle();
          },
        ),
      );
    _loadRequest(url);
  }

  void _loadRequest(String url) async {
    try {
      await _controller.loadRequest(Uri.parse(url));
      // await getScope().delay(1000);
      // _controller.runJavaScript("""
      // sessionStorage.setItem('lang', '1');
      // """);
      // _controller.reload();
    } catch (e) {
      LogUtils.e(e);
    }
  }

  @override
  PreferredSizeWidget createAppbar() => VkAppBar(
        title: Obx(() => appBarTitle(title.value)),
        bottom: ObxSize(
            () => _isLoading.value
                ? LinearProgressIndicator(
                    value: _loadingProgress.value / 100,
                    valueColor: AlwaysStoppedAnimation<Color>(ColorsApp.primaryColor),
                    backgroundColor: Colors.grey,
                  )
                : SizedBox.shrink(),
            Size.fromHeight(4.0)),
      );

  @override
  Widget buildWidget(BuildContext context) {
    return WebViewWidget(controller: _controller);
  }
}
